<script setup>
	import { io } from 'socket.io-client'
	import { useUserStore } from '@/stores'
	import { ref } from 'vue'
	import patientInfo from './components/patient-info.vue'
	import notifyInfo from './components/notify-info.vue'
	import messageInfo from './components/message-info.vue'
	import prescriptionInfo from './components/prescription-info.vue'
	import rateInfo from './components/rate-info.vue'
	import roomStatus from './components/room-status.vue'
  import { getOrderDetail } from '@/apis/consult'
import dayjs from 'dayjs'
	const store = useUserStore()
	const props = defineProps({
		orderId: String
	})
	
	//定义输入框信息
	const textarea=ref('')
	// 建立 socket 连接
	const socket = io('https://consult-api.itheima.net', {
		auth: { token: 'Bearer ' + store.user.token },
		query: { orderId: props.orderId },
		transports: ['websocket', 'polling'],
		timeout: 5000
	})

	const messageList = ref([])

	// 接收历史聊天记录
	socket.on('chatMsgList', (res) => {
		//关闭下拉刷新
		refresherTriggered.value=false
		//定义空数组进行分段数据
		const tempList=[]
		// 提取列表数据
		res.data.forEach((item,index) => {
			//判断是不是数组的第一个元素
			if(index===0) lastTime.value=item.createTime
			// 时间分段
			tempList.push({
			  msgType:31,
				msg:{content:item.createTime},
				id:item.createTime
			},
				...item.items
			)
		})
	  //没有历史聊天记录
		if(tempList.length===0) return uni.showToast({
			icon:'none',
			title:'没有历史聊天记录'
		})
		messageList.value.unshift(...tempList)
	})
	
	//接收对话消息
	socket.on('receiveChatMsg',(message)=>{
		// console.log(message);
		//修改消息为已读
		socket.emit('updateMsgStatus',message.id)
		messageList.value.push(message)
	})
	

	//定义问诊详情
	const orderConsultDetail=ref({})
	const orderDetail=async()=>{
		const res=await getOrderDetail(props.orderId)
		// console.log(res);
		orderConsultDetail.value=res.data
	}
	orderDetail()
	
	// 监听订单状态变化
	socket.on('statusChange',orderDetail)
	
	//发送文字消息
	const onChangeIpt=()=>{
		const store=useUserStore()
		socket.emit('sendChatMsg',{
			from:store.user.id,
			to:orderConsultDetail.value.docInfo.id,
			msgType:1,
			msg:{
				content:textarea.value
			}
		})
		textarea.value=''
	}
	
	//发送图片消息
	const onImg=()=>{
		 // 是否在问诊状态中...
		if(orderConsultDetail.value.status!==3){
		   return uni.showToast({
				icon:'none',
				title:'医生还没接诊'
			})
		}
	 uniCloud.chooseAndUploadFile({
	 	type:'image',
		extension:['.jpg', '.png', '.gif','webp','jpeg'],
		success: (res) => {
			console.log(res);
			socket.emit('sendChatMsg',{
				from:store.user.id,
				to:orderConsultDetail.value.docInfo.id,
				msgType:4,
				msg:{
					picture:{
						id:res.tempFiles[0].lastModified,
						url:res.tempFiles[0].url
					}
				}
			})
		}
	 })
	}
	
	//获取当前时间
	const lastTime=ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
	
	//定义自定义下拉刷新状态
	const refresherTriggered=ref(false)
	//触发下拉刷新事件
	const onRefresherrefresh=()=>{
		//开启下拉刷新
		refresherTriggered.value=true
		// 获取历史聊天记录
		socket.emit('getChatMsgList', 20, lastTime.value, props.orderId); 
	}
</script>
<template>
	<view class="room-page">
		<scroll-view
			refresher-enabled
			:refresher-triggered="refresherTriggered"
			@refresherrefresh="onRefresherrefresh"
			refresher-background="#f2f2f2"
			scroll-y
			style="flex: 1; overflow: hidden"
		>
		<!-- 问诊订单状态 -->
		<room-status :status="orderConsultDetail?.status" :statusValue="orderConsultDetail?.statusValue" :countdown="orderConsultDetail?.countdown"></room-status>
			<view class="message-container">
				<!-- 此处将来填充更多代码... -->
				<template v-for="item in messageList" :key="item.id">		
					<!-- 患者卡片 -->
					<patientInfo v-if="item.msgType === 21" :info="item.msg.consultRecord"></PatientInfo>
					<!-- 通知消息 -->
					<notifyInfo v-if="item.msgType>=31" :msgType="item.msgType" :msg="item.msg.content"></notifyInfo>
				  <!-- 	文字图片消息 -->
					<messageInfo v-if="item.msgType<=4" :msgType="item.msgType" :text="item"></messageInfo>
					<!-- 处方卡片 -->
					<prescriptionInfo v-if="item.msgType===22" :msgType="item.msgType" :info="item.msg.prescription"></prescriptionInfo>
					<!-- 评价卡片 -->
					<!-- 未评价 -->
					<rateInfo v-if="item.msgType===23" :orderId="props.orderId" :docId="orderConsultDetail.docInfo.id" :hasEvaluate="false"></rateInfo>
					<!-- 已评价 -->
					<rateInfo v-if="item.msgType===24" :hasEvaluate="true" :evaluateDoc="item.msg.evaluateDoc"></rateInfo>
				</template>
			</view>
		</scroll-view>

		<!-- 发送消息 -->
		<view class="message-bar">
			<template v-if="true">
				<uni-easyinput
				  v-model="textarea"
					:disabled="orderConsultDetail.status!==3"
					:clearable="false"
					:input-border="false"
					placeholder-style="font-size: 32rpx; color: #c3c3c5;"
					placeholder="问医生"
					@confirm="onChangeIpt"
				/>
				<view class="image-button" @click="onImg">
					<uni-icons size="40" color="#979797" type="image"></uni-icons>
				</view>
			</template>
			<button v-else class="uni-button">咨询其它医生</button>
		</view>
	</view>
</template>

<style lang="scss">
	@import './index.scss';
</style>
